package com.greenantmall.utils;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.greenantmall.bean.Order;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class AlipayUtils {
	private Activity mActivity;
	private LinkedList<AVObject> mCreatedOrdersList = new LinkedList<AVObject>();
	private PayCompleteListener mPayCompletListener;
	private Handler mHandler = new Handler(Looper.getMainLooper());

	public AlipayUtils(Activity activity, List<AVObject> createdOrdersList,
			PayCompleteListener listener) {
		this.mActivity = activity;
		this.mCreatedOrdersList.addAll(createdOrdersList);
		Log.d("CEXX", "CEXX => AlipayUtils => mCreatedOrdersList.size : " + mCreatedOrdersList.size());
		
		this.mPayCompletListener = listener;
	}

	public void alipay() {
		Log.d("CEXX", "CEXX => AlipayUtils => AlipayManager => pay");
		getDataFromNet();
	}

	private void getDataFromNet() {
		Log.d("CEXX", "CEXX => AlipayUtils => getDataFromNet");
		if (mCreatedOrdersList.size() == 0) {
			if (mPayCompletListener != null) {
				mPayCompletListener.payComplete();
			}
			return;
		}

		final AVObject orderItem = mCreatedOrdersList.poll();
		final String orderId = orderItem.getString(Order.ATTR_ORDERID);
		final double totalCost = orderItem.getDouble(Order.ATTR_TOTALCOST);

		String userId = AVUser.getCurrentUser().getObjectId();
		String url = "http://greenantmall.net/sgz/unionPay.action?";
		HttpUtils httpUtils = new HttpUtils();

		RequestParams params = new RequestParams();
		params.addBodyParameter("trans_id", orderId);
		params.addBodyParameter("user_id", userId);
		params.addBodyParameter("money", String.valueOf(totalCost));
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Log.d("CEXX", "CEXX => getDataFromNet => arg0 : " + arg0);
						Log.d("CEXX", "CEXX => getDataFromNet => arg1 : " + arg1);
						getDataFromNet();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						Log.d("CEXX", "CEXX => getDataFromNet => result : " + result);
						toAlipay(result);
					}
				});
	}

	private void toAlipay(final String payInfo) {
		Log.d("CEXX", "CEXX => AlipayUtils => toAlipay => payInfo : " + payInfo);
		try {
			Runnable payRunnable = new Runnable() {
				@Override
				public void run() {
					// 构造PayTask 对象
					PayTask alipay = new PayTask(mActivity);
					// 调用支付接口，获取支付结果
					final String result = alipay.pay(payInfo, true);
					Log.d("CEXX", "CEXX => AlipayUtils => toAlipay => result : " + result);
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							AliPayResult payResult = new AliPayResult(result);
							String resultInfo = payResult.getResult();// 同步返回需要验证的信息
							Log.d("CEXX", "CEXX => AlipayUtils => toAlipay => resultInfo : " + resultInfo);

							String resultStatus = payResult.getResultStatus();
							Log.d("CEXX", "CEXX => AlipayUtils => toAlipay => resultStatus : " + resultStatus);
							// 判断resultStatus
							// 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
							if (TextUtils.equals(resultStatus, "9000")) {
								UtilTools.showMyToast(mActivity, "支付成功");
							} else {
								// 判断resultStatus 为非"9000"则代表可能支付失败
								// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
								if (TextUtils.equals(resultStatus, "8000")) {
									UtilTools.showMyToast(mActivity,
											"支付结果确认中");
								} else {
									// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
									UtilTools
											.showMyToast(mActivity, "支付失败");
								}
							}
							getDataFromNet();
						}
					});
				}
			};

			// 必须异步调用
			Thread payThread = new Thread(payRunnable);
			payThread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class AliPayResult {
		private String resultStatus;
		private String result;
		private String memo;

		public AliPayResult(String rawResult) {

			if (TextUtils.isEmpty(rawResult))
				return;

			String[] resultParams = rawResult.split(";");
			for (String resultParam : resultParams) {
				if (resultParam.startsWith("resultStatus")) {
					resultStatus = gatValue(resultParam, "resultStatus");
				}
				if (resultParam.startsWith("result")) {
					result = gatValue(resultParam, "result");
				}
				if (resultParam.startsWith("memo")) {
					memo = gatValue(resultParam, "memo");
				}
			}
		}

		@Override
		public String toString() {
			return "resultStatus={" + resultStatus + "};memo={" + memo + "};result={" + result + "}";
		}

		private String gatValue(String content, String key) {
			String prefix = key + "={";
			return content.substring(content.indexOf(prefix) + prefix.length(),
					content.lastIndexOf("}"));
		}

		/**
		 * @return the resultStatus
		 */
		public String getResultStatus() {
			return resultStatus;
		}

		/**
		 * @return the memo
		 */
		public String getMemo() {
			return memo;
		}

		/**
		 * @return the result
		 */
		public String getResult() {
			return result;
		}
	}
}
